#include "TcpServer.hpp"
#include <memory>
using namespace std;
bool cal(const Request &req, Resposne &res)
{
    int x = req._x;
    int y = req._y;
    char op = req._op;
    switch (op)
    {
    case '+':
    {
        res._exitcode = 0;
        res._result = x + y;
        return true;
    }
    case '-':
    {
        res._exitcode = 0;
        res._result = x - y;
        return true;
    }
    case '*':
    {
        res._exitcode = 0;
        res._result = x * y;
        return true;
    }
    case '/':
    {
        if (y == 0)
        {
            res._exitcode = 1;
            cout << "除零错误" << endl;
            return false;
        }
        else
        {
            res._exitcode = 0;
            res._result = x / y;
        }
        return true;
    }
    case '%':
    {
        if (y == 0)
        {
            res._exitcode = 1;
            cout << "模零错误" << endl;
            return false;
        }
        else
        {
            res._exitcode = 0;
            res._result = x % y;
        }
        return true;
    }
    }
}
void calculate(Connection* cnn)
{
    //重复读取信息
    string buffer;
    while(GetOnePackage(cnn->_inbuffer,&buffer))
    {
        //得到信息后去报头
        string Req_str;
        delength(buffer,&Req_str);
        //得到信息后进行反序列号
        Request req;
        req.deserialization(Req_str);
        //传入函数进行计算
        Resposne res;
        cal(req,res);
        logMessage(NORMAL,"计算完成");
        //吧计算结果进行序列化再加报头
        string Res_str;
        res.serialization(&Res_str);
        cnn->_outbuffer += enlength(Res_str);
        logMessage(NORMAL,"报文组装完成");
        //进行发送
        if(cnn->_sender)
        cnn->_sender(cnn);
        logMessage(NORMAL,"发送完成");
        //如果没发完就把fd交给epoll帮我关心
        if(!cnn->_outbuffer.empty())
        cnn->_tsp->EnableReaderWriter(cnn,true,true);
    }
}
int main()
{
    unique_ptr<TcpServer> ptr(new TcpServer(calculate));
    ptr->InitServer();
    ptr->Dispatcher();
}